package Lib

import (
	"github.com/streadway/amqp"
	"log"
	"strings"
	"wskyygyso/casually/AppInit"
)

type MQ struct {
	Channel *amqp.Channel
}

func NewMQ() *MQ {
	channel, err := AppInit.GetConn().Channel()
	if err != nil {
		log.Println(err)
		return nil
	}
	return &MQ{
		Channel: channel,
	}
}

func (m *MQ) DecQueueAndBind(queues string, routeKey string, exChange string) error {
	queueSplit := strings.Split(queues, ",")
	for _, queue := range queueSplit {
		q, err := m.Channel.QueueDeclare(queue, false, false, false, false, nil)
		if err != nil {
			return err
		}
		err = m.Channel.QueueBind(q.Name, routeKey, exChange, false, nil)
		if err != nil {
			return err
		}
	}
	return nil
}

func (m *MQ) SendMessage(routeKey string, exChange string, msg string) error {
	return m.Channel.Publish(exChange, routeKey, false, false, amqp.Publishing{
		ContentType: "text/plain",
		Body:        []byte(msg),
	})
}
